using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;


namespace GameUI {
	public class UpgradeSelectable:MonoBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler {
		void Start() {
			image=GetComponent<Image>();
			image.sprite=upgrade.upgradeData.sprite;
			Select+=SeleceEventHandler;
		}
		void Update() {
			UpdateStateOffset();
		}

		public static System.EventHandler<PointerEventData> Select;
		public static System.EventHandler<PointerEventData> Preview;
		public static System.EventHandler<PointerEventData> EndPreview;
		void OnSelect(PointerEventData e) { if(Select!=null) Select(this,e); }
		void OnEndPreview(PointerEventData e) { if(Select!=null) EndPreview(this,e); }
		void OnPreview(PointerEventData e) { if(Select!=null) Preview(this,e); }

		static GameObject upgradeSelectablePrefab;
		public static UpgradeSelectable Create(Vector2 position,UpgradeInstance upgrade,Transform parent) {
			if(upgradeSelectablePrefab==null) upgradeSelectablePrefab=Resources.Load<GameObject>("UpgradeSelectable");
			GameObject resultGameObject = Instantiate(upgradeSelectablePrefab,parent);
			resultGameObject.transform.localPosition=position;

			UpgradeSelectable result = resultGameObject.GetComponent<UpgradeSelectable>();
			result.upgrade=upgrade;
			return result;
		}

		public enum State {
			Default,
			Selected,
			Selecting
		}
		State state;
		State statePrevious;
		Vector2 StateOffset(State state) {
			switch(state) {
			case State.Selected:
				return new Vector2(0,0.2f);
			case State.Selecting:
				return new Vector2(0,0.1f);
			default:
				return new Vector2(0,0);
			}
		}

		public UpgradeInstance upgrade { get; private set; }
		Image image;

		void UpdateStateOffset() {
			if(statePrevious!=state) {
				transform.position-=(Vector3)StateOffset(statePrevious);
				transform.position+=(Vector3)StateOffset(state);
				statePrevious=state;
			}
		}

		int eventCallTimes;
		void IPointerClickHandler.OnPointerClick(PointerEventData e) {
			OnSelect(e);
			state=State.Selected;
		}
		void IPointerEnterHandler.OnPointerEnter(PointerEventData e) {
			if(state==State.Default) {
				state=State.Selecting;
				OnPreview(e);
			}
		}
		void IPointerExitHandler.OnPointerExit(PointerEventData e) {
			if(state==State.Selecting) {
				state=State.Default;
				OnEndPreview(e);
			}
		}

		void SeleceEventHandler(object sender,PointerEventData e) {
			UpgradeSelectable selectable = sender as UpgradeSelectable;
			if(selectable==null) return;
			if(selectable==this) return;
			state=State.Default;
		}
	}
}